package com.shaoshaohuo.app.ui;

import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.utils.city.Cityinfo;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.Lineinfo;
import com.shaoshaohuo.app.entity.UserInfoEntity;
import com.shaoshaohuo.app.net.HttpRequest.RequestListener;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.adapter.RunlineAdapter;
import com.shaoshaohuo.app.view.TopbarView;
import com.shaoshaohuo.app.view.swipemenu.SwipeMenu;
import com.shaoshaohuo.app.view.swipemenu.SwipeMenuCreator;
import com.shaoshaohuo.app.view.swipemenu.SwipeMenuItem;
import com.shaoshaohuo.app.view.swipemenu.SwipeMenuListView;
import com.shaoshaohuo.app.view.swipemenu.SwipeMenuListView.OnMenuItemClickListener;
import com.shaoshaohuo.app.utils.CityinfoUtil;
import com.shaoshaohuo.app.utils.StringHelper;
import com.shaoshaohuo.app.view.citymenu.CascadingMenuPopWindow;
import com.shaoshaohuo.app.view.citymenu.interfaces.CascadingMenuViewOnSelectListener;
import com.shaoshaohuo.app.view.citymenu.entity.Area;

import java.util.List;

public class RunLineActivity extends BaseActivity {

    private static final int REQUEST_CODE_START = 100;
    private static final int REQUEST_CODE_END = 101;
	private Cityinfo mStartCity; //开始的市
	private Cityinfo mEndCity; //结束的市
    
	private TopbarView mTopbarView;
	private SwipeMenuListView mAddressListview;
	private View mSaveLayout;
	private Button mSaveButton;

	private TextView mStartCityText;
	private TextView mEndCityText;
	
    private RunlineAdapter<Lineinfo> mAdapter;
    private List<Lineinfo> lineinfo;
    
    private String lastStartCityCode;
    private String lastEndCityCode;
    private CascadingMenuPopWindow cascadingMenuPopWindow;
	private CascadingMenuPopWindow cascadingMenuPopWindowStart;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_run_line);
		initView();
		setUpView();
		requestData();
		
		setResult(RESULT_OK);
	}
	
	private void requestData() {
        startLoadingDialog();
        RequestService.getInstance().getUserInfo(this, UserInfoEntity.class, new RequestListener() {
            
            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                dismissLoadingDialog();
                if(resultData.isOk()){
                    UserInfoEntity entity = (UserInfoEntity) resultData;
                    setAdapter(entity);
                }else{
                    showToast(resultData.getMsg());
                }
            }
            
            @Override
            public void onFailed(int requestCode, Exception error, String msg) {
                dismissLoadingDialog();
                showToast(R.string.please_check_network);
            }
        });
    }

	protected void setAdapter(UserInfoEntity entity) {
	    lineinfo = entity.getData().getLineinfo();
	    if(mAdapter == null){
	        mAdapter = new RunlineAdapter<>(this, lineinfo, false);
	        mAddressListview.setAdapter(mAdapter);
	    }else{
	        mAdapter.setData(lineinfo);
	    }
	}

    private void initView() {
		mTopbarView = (TopbarView) this.findViewById(R.id.topbar);

		mAddressListview = (SwipeMenuListView) this.findViewById(R.id.listview_address_list);
		mSaveLayout = this.findViewById(R.id.layout_save);
		mSaveButton = (Button) this.findViewById(R.id.button_save);
		
		mStartCityText = (TextView) this.findViewById(R.id.textview_start_city);
		mEndCityText = (TextView) this.findViewById(R.id.textview_end_city);
	}

	private void setUpView() {
		mTopbarView.setCenterText("常跑路线");
		mTopbarView.setLeftView(true, true);
		mTopbarView.setRightText("添加");
		mTopbarView.setRightClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mSaveLayout.setVisibility(mSaveLayout.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
			}
		});


		SwipeMenuCreator creator = new SwipeMenuCreator() {

            @Override
            public void create(SwipeMenu menu) {
                // create "delete" item
                SwipeMenuItem deleteItem = new SwipeMenuItem(
                        getApplicationContext());
                // set item background
                deleteItem.setBackground(new ColorDrawable(Color.parseColor("#FF6368")));
                // set item width
                deleteItem.setWidth(StringHelper.dip2px(RunLineActivity.this,50));
                // set a icon
                deleteItem.setIcon(R.drawable.icon_delete);
                
                // add to menu
                menu.addMenuItem(deleteItem);
            }
        };
        // set creator
        mAddressListview.setMenuCreator(creator);
        
        mAddressListview.setOnMenuItemClickListener(new OnMenuItemClickListener() {
            
            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
                Lineinfo line = lineinfo.get(position);
                showDialog("确定删除此条路线吗？", line.getId());
                return false;
            }
        });
		
		mSaveLayout.setVisibility(View.GONE);
		mStartCityText.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//TODO
				//selectCity(REQUEST_CODE_START);
				showCityDialog(REQUEST_CODE_START);
			}
		});
		mEndCityText.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//TODO
				//selectCity(REQUEST_CODE_END);
				showCityDialog(REQUEST_CODE_END);
			}
		});
		mSaveButton.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
           /*     if(startProvince == null || startCity==null){
                    showToast("--");
                    return;
                }
                if(endProvince == null || endCity==null){
                    showToast("---");
                    return;
                }
                saveRunline(startProvince.getProid(),startCity.getCitycode(),endProvince.getProid(),endCity.getCitycode());*/
            	 if(mStartCity==null){
                     showToast("--");
                     return;
                 }
                 if(mEndCity==null){
                     showToast("---");
                     return;
                 }
                 saveRunline(mStartCity.getId(),mEndCity.getId());
            	
            }
        });
		
	}
	
	private void showDialog(String message, final String id) {
        Builder builder = new Builder(this);
        builder.setMessage(message);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                deleteLine(id);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.create().show();
    }
	
	private void deleteLine(String id){
	    RequestService.getInstance().deleteLine(this, id, BaseEntity.class, new RequestListener() {
            
            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                dismissLoadingDialog();
                if(resultData.isOk()){
                    showToast("刪除成功");
                    mSaveLayout.setVisibility(View.GONE);
                    requestData();
                }else{
                    showToast(resultData.getMsg());
                }
            }
            
            @Override
            public void onFailed(int requestCode, Exception error, String msg) {
                dismissLoadingDialog();
                showToast(R.string.please_check_network);
            }
        });
	}

	protected void saveRunline(String fromcityid, String tocityid) {
	    startLoadingDialog();
	    if(fromcityid.equals(lastStartCityCode) && tocityid.equals(lastEndCityCode)){
	    	showToast("该条常跑线路已设置，无须重复设置。");
	    	dismissLoadingDialog(); 
	    	return;
	    }else{
	    	lastStartCityCode = fromcityid;
	    	lastEndCityCode = tocityid;
	    }
	    
	    RequestService.getInstance().saveLine(this, fromcityid, tocityid, BaseEntity.class, new RequestListener() {
            
            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                dismissLoadingDialog();
                if(resultData.isOk()){
                    showToast("添加成功");
                    requestData();
                }else{
                    showToast(resultData.getMsg());
                }
            }
            
            @Override
            public void onFailed(int requestCode, Exception error, String msg) {
             dismissLoadingDialog();   
             showToast(R.string.please_check_network);
            }
        });
	}

 /*   private void selectCity(int requestCode) {
		Intent intent = new Intent(this,SelectProvinceActivity.class);
		startActivityForResult(intent, requestCode);
	}*/
	
/*	@Override
    protected void onActivityResult(int arg0, int arg1, Intent arg2) {
        super.onActivityResult(arg0, arg1, arg2);
        if(arg1 == RESULT_OK && arg2 != null){
            
            switch (arg0) {
            case REQUEST_CODE_START:
                startProvince = (Province) arg2.getSerializableExtra(ExtraName.province);
                startCity = (City) arg2.getSerializableExtra(ExtraName.city);
                
                mStartCityText.setText(startCity.getCityname());
                
                break;
            case REQUEST_CODE_END:
                endProvince = (Province) arg2.getSerializableExtra(ExtraName.province);
                endCity = (City) arg2.getSerializableExtra(ExtraName.city);
                
                mEndCityText.setText(endCity.getCityname());
                break;
            }
            
            
        }
    }*/
	
	
	
	/*
	 * 获取三级联动
	 */
	private void showCityDialog(int REQUEST_CODE) {
		switch (REQUEST_CODE) {
		case REQUEST_CODE_START:
			StartDialog();
			break;
		case REQUEST_CODE_END:
			EndDialog();
			break;
		}
			
		
	}

	/**
	 * 显示开始
	 */
	private void StartDialog() {

		if (cascadingMenuPopWindowStart == null) {
			//向三级menu添加地区数据
			cascadingMenuPopWindowStart = new CascadingMenuPopWindow(this, false);
			cascadingMenuPopWindowStart
					.setMenuViewOnSelectListener(new CascadingMenuViewOnSelectListener() {
						@Override
						public void getValue(Area city, String fullname) {
							mStartCity = CityinfoUtil.convert(city);
							if (mStartCity == null) {
								mStartCityText.setText(fullname);
							} else {
								mStartCityText.setText(mStartCity.getCity_name());
							}
						}
					});
			cascadingMenuPopWindowStart.showAsDropDown(mStartCityText, 5, 5);
		} else if (cascadingMenuPopWindowStart != null
				&& cascadingMenuPopWindowStart.isShowing()) {
			cascadingMenuPopWindowStart.dismiss();
		} else {
			cascadingMenuPopWindowStart.showAsDropDown(mStartCityText, 5, 5);
		}
	}
	
	/**
	 * 显示结束
	 */
	private void EndDialog() {

		if (cascadingMenuPopWindow == null) {
			//向三级menu添加地区数据
			cascadingMenuPopWindow = new CascadingMenuPopWindow(this);
			cascadingMenuPopWindow
					.setMenuViewOnSelectListener(new CascadingMenuViewOnSelectListener() {
						@Override
						public void getValue(Area city, String fullname) {
							mEndCity = CityinfoUtil.convert(city);
							if (mEndCity == null) {
								mEndCityText.setText(fullname);
							} else {
								mEndCityText.setText(mEndCity.getCity_name());
							}
						}
					});
			cascadingMenuPopWindow.showAsDropDown(mEndCityText, 5, 5);
		} else if (cascadingMenuPopWindow != null
				&& cascadingMenuPopWindow.isShowing()) {
			cascadingMenuPopWindow.dismiss();
		} else {
			cascadingMenuPopWindow.showAsDropDown(mEndCityText, 5, 5);
		}
	}
	
	@Override
	protected void onDestroy() {
		if (cascadingMenuPopWindow != null) {
			cascadingMenuPopWindow.dismiss();
		}
		if (cascadingMenuPopWindowStart != null) {
			cascadingMenuPopWindowStart.dismiss();
		}
		super.onDestroy();
	}
}
